from docx import Document
from openpyxl import Workbook


def word_tables_to_excel_transposed(word_path, excel_path):
    """
    将Word文档中的所有表格转置（行转列）后转换为Excel文件
    参数:
        word_path (str): Word文档路径
        excel_path (str): 生成的Excel文件路径
    """
    # 读取Word文档
    doc = Document(word_path)

    # 创建Excel工作簿
    wb = Workbook()
    ws = wb.active
    ws.title = "转置数据"

    # 遍历所有表格
    for table_idx, table in enumerate(doc.tables, 1):
        # 存储表格数据用于转置
        table_data = []

        # 提取表格数据
        for row in table.rows:
            # 处理包含多段落的单元格
            row_data = [
                '\n'.join([para.text for para in cell.paragraphs])
                for cell in row.cells
            ]
            table_data.append(row_data)

        # 执行行转列操作
        if table_data:
            # 使用zip进行矩阵转置
            transposed_data = list(zip(*table_data))

            # 写入转置后的数据
            for col_idx, column in enumerate(transposed_data, 1):
                if table_idx > 1:
                    if col_idx == 2:
                        ws.append(column)
                else:
                    ws.append(column)

                # （可选）添加表头标识
                # if col_idx == 1:
                #     ws.cell(row=1, column=col_idx).value = f"表格{table_idx}标题"

        # 在表格之间添加两个空行
        # if table_idx < len(doc.tables):
        #     ws.append([])
        #     ws.append([])

    # 自动调整列宽
    for column in ws.columns:
        max_length = 0
        column = list(column)
        for cell in column:
            try:
                if len(str(cell.value)) > max_length:
                    max_length = len(cell.value)
            except:
                pass
        adjusted_width = (max_length + 2) * 1.2
        ws.column_dimensions[column[0].column_letter].width = adjusted_width

    # 保存Excel文件
    wb.save(excel_path)


if __name__ == "__main__":
    word_tables_to_excel_transposed(
        word_path="C:\\68.docx",
        excel_path="C:\\68_transposed_output.xlsx"
    )